import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { downloadType } from '@/utils/utils'
import { exportExcel } from './excel'
import JSZip from 'jszip'

type K = {
  uid: string
  name: string
  status: string
  url: string
  thumbUrl: string
}
// 单个文件下载
const downloadFile = async (file: K) => {
  const sufix = process.env.VUE_APP_IMAGE_URL
  const fileName = file.name
  const path = file.thumbUrl.split(`${sufix}`)[1]?.split('.')[1]
  if (!path) return console.log('下载地址错误')
  NProgress.start()
  try {
    const response = await fetch(file.thumbUrl, { mode: 'no-cors' })
    const buffer = await response.arrayBuffer()
    if (path === 'xlsx') {
      exportExcel(buffer, fileName + '.xlsx')
    } else {
      const type = path ? downloadType[path] : ''
      const blob = new Blob([buffer], { type })
      const reader = new FileReader()
      reader.readAsDataURL(blob)
      reader.onload = () => {
        const link = document.createElement('a')
        link.href = reader.result as string
        link.download = fileName
        link.click()
      }
    }
    console.log('下载成功')
  } catch (error) {
    console.log(fileName + '下载失败')
  } finally {
    NProgress.done()
  }
}
// 多个文件下载成ZIP
export const downloadZip = async (file: K[], folderName: string) => {
  const sufix = process.env.VUE_APP_IMAGE_URL
  NProgress.start()
  const zip = new JSZip()
  try {
    for (let i = 0; i < file.length; i++) {
      const url = file[i]
      const path = url.thumbUrl.split(`${sufix}`)[1]?.split('.').pop()
      if (!path) continue // 跳过错误的地址
      const response = await fetch(url.thumbUrl)
      const buffer = await response.arrayBuffer()
      const fileName = url.name + (path ? `.${path}` : '') // 生成唯一文件名

      if (path === 'xlsx') {
        exportExcel(buffer, fileName) // 导出 Excel 文件
      } else {
        const type = path ? downloadType[path] : 'application/octet-stream'
        const blob = new Blob([buffer], { type })
        zip.file(fileName, blob) // 将文件添加到 ZIP
      }
    }
    // 生成 ZIP 文件并下载
    zip.generateAsync({ type: 'blob' }).then((content: any) => {
      const link = document.createElement('a')
      link.href = URL.createObjectURL(content)
      link.download = folderName + '.zip' // 提供下载的 ZIP 文件名称
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) // 下载后移除链接
      URL.revokeObjectURL(link.href) // 释放内存
    })
  } catch (error) {
    console.error('文件下载失败:', error)
  }
  NProgress.done()
}
export default downloadFile
